<template>
  <view class="containerDoc">
    <view class="page-container" :style="listHeightStylePage">
      <!-- 导航栏 -->
      <u-navbar :title="buttonTip" placeholder @leftClick="back" :border="false" :shadow="true"></u-navbar>
      <view style="padding: 20rpx;" :style="listHeightStyle">
        <web-view id="Faceregistration" ref="Faceregistrationwebview" :src="FaceRul" @message="handleMessage"></web-view>
      </view>
    </view>



    <up-modal :show="show" :title="title" :content='content' @confirm="Faceconfirm">
      <view class="slot-content">
        <rich-text :nodes="content"></rich-text>
      </view>
    </up-modal>


    <!-- 消息提示	 -->
    <u-toast ref="uToast" />
  </view>
</template>
<script>
import {mapStores} from "pinia";
import {useClockStore, useUserStore, useLoginStore} from "@/pinia-store/user";
import clock from "@/apis/cloud/clock";

export default {
  data(){
    return {
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      appHeight: null,
      topHeight: 0,
      listHeightStylePage: {},
      scrollViewHeight: {}, // 动态计算 scroll-view 的高度
      FaceRul:'/hybrid/html/Faceregistration.html',
      show:false,
      title:'',
      content:'',
      isfirstrlsbstatus:0,
      buttonTip:'',
    }
  },
  computed: {
    ...mapStores(useUserStore, useClockStore)
  },
  onLoad (value) {
    this.isfirstrlsbstatus = value.isfirstrlsbstatus || 1
    if(value.isfirstrlsbstatus == 1){
      this.buttonTip = '人脸认证打卡'
    }else{
      this.show = true
      this.buttonTip = '上传人脸注册'
      this.title =  '上传人脸提示'
      this.content = '您尚未注册人脸信息，请上传清晰的人脸照片，用于后续打卡认证。'
    }
    this.isfirstrlsbstatus = value?.isfirstrlsbstatus
  },
  async mounted () {
    window.addEventListener("message", this.handleMessage);
  },
  onUnload(){
    // 移除事件监听
    window.removeEventListener('message', this.handleMessage);
  },
  async created() {
    this.appHeight = uni.getSystemInfoSync();
    this.topHeight = this.appHeight.screenHeight;
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif
    // #ifdef APP-PLUS
    this.listHeightStylePage = {
      height: `${this.topHeight}px`,
    };
    // #endif
    await this.calculateListHeight();
  },
  methods: {
    // 处理从 local.html 接收的经纬度
    async handleMessage (event) {
      if (event.data && event.data.type === 'getFaceregistration') {
        try {
          this.handleSetTime(event.data.params)
        } catch (error) {
          console.error('Failed to parse position:', error);
        }
      }
    },
    calculateListHeight() {
      const windowHeight = window.innerHeight; // 视口高度
      const navbarHeight = 52; // 导航栏高度（假设为 44px）
      const tabsHeight = 88;
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        height: `${this.topHeight - 164}px`,
        overflowY: 'auto'
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'auto'
      };
      // #endif
    },

    Faceconfirm(){
      if(this.content == '上传人脸成功'){
        this.show = false
        this.isfirstrlsbstatus = 1
        uni.$emit('backisfirstrlsbstatus');
        this.back()
      }else{
        this.show = false
      }
    },
    resertAll() {
      this.buttonTip =   this.isfirstrlsbstatus == 1 ? "开始人脸识别" : "上传人脸"
      this.snapshotInfo = '' // 快照信息
      this.showCountDown = false // 拍摄倒计时
      this.timeOut = this.snapCountdownTimer
      this.isPass = null // 是否通过人脸认证
    },
    startPreview() {
      const _that = this
      _that.handleSetTime()
    },

    handleSetTime(filePath) {
      this.$refs.uToast.show({
        icon: false,
        message: this.isfirstrlsbstatus == 1 ? '人脸认证中...' : '上传人脸中...',
        duration: -1
      })

      uni.uploadFile({
        url: 'https://cloud.mfarmers.com/dist/interface/public/index.php/index/Kaoqin/rlsb_upload',
        filePath: filePath,
        formData: {
          'phone': this.userStore.user.phone,
          'worker_id': this.userStore.user.worker_id,
		  'token': useLoginStore().token
        },
        name: "file",
        success: (uploadFileRes) => {
          const upData = JSON.parse(uploadFileRes.data)
          console.log('===上传结果===', upData)

          // 第一次
          if(upData.status == 1 && upData.flag == 1) {
            clock.faceCheck(upData.jichu_path).then(res => {
              if(res.data == 1) {
                if(this.isfirstrlsbstatus == 0){
                  this.$refs.uToast.hide()
                  this.show = true
                  this.content = '上传人脸成功'
                }else{
                  // 检测成功
                  clock.addClockRecord(this.clockStore.clock).then(resadd => {
                    if(resadd.status == 1){
                      this.$refs.uToast.hide();
                      setTimeout(() => {
                        uni.$emit('back');
                        uni.$emit('backisfirstrlsbstatus');
                        uni.navigateBack();
                      }, 200)
                    }else{
                      this.$refs.uToast.hide()
                      uni.$u.toast(resadd.msg || '打卡失败，请重新打卡');
                    }
                    
                  }).catch(()=>{
                    this.$refs.uToast.hide()
                    uni.$u.toast('打卡失败，请重新打卡');
                  })
                }

              }else {
                // 检测不是人脸从新扫脸
                clock.rlsbDelete({phone: this.userStore.user.phone}).then(del => {
                  this.$refs.uToast.hide()
                  uni.$u.toast('未检测到人脸，请保持正脸在取景框中');
                })
              }
            }).catch(err => {
              this.$refs.uToast.hide()
              uni.$u.toast('未检测到人脸，请保持正脸在取景框中');
            })
          }

          // 人脸比对  isfirstrlsbstatus == 1 有人脸
          if(upData.status == 1 && upData.flag == 2) {
            console.log('111111111111')
              const data = {
                file1: upData.jichu_path,
                file2: upData.duibi_path,
              }

              clock.hwfaceRlsb(data).then(res => {
                console.log('===比对结果===', res)
                const result = (+res.data).toFixed(2);

                // 人脸比对成功
                if(0.4 > +result) {

                  // console.log('this.clockStore.clock', this.clockStore.clock)

                  clock.addClockRecord(this.clockStore.clock).then(resadd => {
                     if(resadd.status == 1){
                      this.$refs.uToast.hide()
                      setTimeout(() => {
                        uni.$emit('back');
                        uni.$emit('backisfirstrlsbstatus');
                        uni.navigateBack();
                      }, 200)
                    }else{
                      this.$refs.uToast.hide()
                      uni.$u.toast(resadd.msg || '打卡失败，请重新打卡');
                    }
                  }).catch(()=>{
                    this.$refs.uToast.hide()
                    uni.$u.toast('打卡失败，请重新打卡');
                  })
                }else {
                  // 大于35
                  this.$refs.uToast.hide()
                  uni.$u.toast('人脸比对失败，请重新扫脸打卡');
                }

              }).catch(err => {
                this.$refs.uToast.hide()
                uni.$u.toast('人脸比对失败，请重新扫脸打卡');
              })
            }

        },
        fail: (error) => {
        },
        complete: () => {
        }
      });

    },

    back(){
      uni.navigateBack();
    }

  },
}
</script>

<style scoped lang="scss">
.containerDoc{
  overflow: hidden;
  background-color: #f3f4f5;
  .page-container {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
}
</style>
